﻿using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;
using Orchard.UI.Notify;
using Dyn.News.Models;
using Orchard;
using System.Linq;
using Dyn.News.ViewModels;
using Orchard.Data;
using System.Collections.Generic;
using Dyn.Media.Models;
using Dyn.Media.Settings;
using Dyn.Media.ViewModels;
using Dyn.Media.Services;
using Dyn.News.Services;
using Orchard.Security;
namespace Dyn.Ecommerce.Drivers
{
    [UsedImplicitly]

    public class NewsCategoryWidgetPartDriver : ContentPartDriver<NewsCategoryWidgetPart>
    {
        private readonly INotifier _notifier;
        private const string TemplateName = "Parts/ECategoryWidgetPart";
        private readonly IOrchardServices _service;
        private readonly IMediaListService _mediaListService;
        private readonly ICategoryervice _categorySVC;
        private readonly IRepository<NewsContentCategoryWidgetRecord> _categoryWidget;
        private readonly IAuthorizationService _authorSvc;
        public Localizer T { get; set; }

        public NewsCategoryWidgetPartDriver(INotifier notifier,
            IOrchardServices service,
            IRepository<NewsContentCategoryWidgetRecord> categoryWidget,
            IMediaListService mediaListService,
            IAuthorizationService authorSvc,
            ICategoryervice categorySVC)
        {
            _authorSvc = authorSvc;
            _categorySVC = categorySVC;
            _mediaListService = mediaListService;
            _categoryWidget = categoryWidget;
            _service = service;
            _notifier = notifier;
            T = NullLocalizer.Instance;
        }

        protected override DriverResult Display(NewsCategoryWidgetPart part, string displayType, dynamic shapeHelper)
        {
            //Lấy ra danh sách category part
            var categoriesVM = _categoryWidget.Fetch(c=> c.NewsCategoryWidgetPartRecord.Id == part.Id).OrderBy(o=> o.DisplayOrder).Join(_service.ContentManager.Query<NewsCategoryPart>().List(),
                (r => r.NewsCategoryPartRecord.Id),
                (p => p.Id),
                (r, p) => new CategoryViewModel
                {
                    CategoryPart = p,
                    CurrentMedia = _categorySVC.GetCurrentMediaFile(p)
                }).ToList();
            var checkUser = _authorSvc.TryCheckAccess(Orchard.Security.StandardPermissions.SiteOwner, _service.WorkContext.CurrentUser, null);
            switch (part.ViewType)
            {
                case ViewType.Grid:
                    return ContentShape("Parts_NewsCategoryWidgetPart_Grid",
                        () => shapeHelper.Parts_NewsCategoryWidgetPart_Grid(WidgetVM: categoriesVM, CheckUser: checkUser));
                case ViewType.List:
                    return ContentShape("Parts_NewsCategoryWidgetPart_List",
                        () => shapeHelper.Parts_NewsCategoryWidgetPart_List(WidgetVM: categoriesVM, CheckUser: checkUser));
                case ViewType.CategorySlider1:
                    return ContentShape("Parts_NewsCategoryWidgetPart_Slider1",
                        () => shapeHelper.Parts_NewsCategoryWidgetPart_Slider1(WidgetVM: categoriesVM));
                case ViewType.CategorySlider2:
                    return ContentShape("Parts_NewsCategoryWidgetPart_Slider2",
                        () => shapeHelper.Parts_NewsCategoryWidgetPart_Slider2(WidgetVM: categoriesVM));
            }
            return ContentShape("Parts_NewsCategoryWidgetPart",
                () => shapeHelper.Parts_NewsCategoryWidgetPart(WidgetVM: categoriesVM));
        }

        protected override DriverResult Editor(NewsCategoryWidgetPart part, dynamic shapeHelper)
        {
            part.CategoryPartViewModels = _categorySVC.GetCategoriesWidget(part).OrderBy(o => o.DisplayOrder).ToList();
            return ContentShape("Parts_NewsCategoryWidgetPart",
                    () => shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: part, Prefix: Prefix));
        }

        protected override DriverResult Editor(NewsCategoryWidgetPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            var ids = new List<NewsContentCategoryWidgetRecord>();
            var categoryMenus = part.CategoryPartViewModels.Where(w => w.Id != 0);
            foreach (var item in categoryMenus)
            {
                //Lấy ra menu tren giao dien
                var catwg = part.Record.ContentCategoryWidgets.Where(p => p.NewsCategoryPartRecord.Id == item.Id && p.NewsCategoryWidgetPartRecord.Id == part.Record.Id);
                //Nếu có chọn menu
                if (catwg.Count() > 0)
                {
                    //Lấy ra record của ContentMenuWidgets
                    NewsContentCategoryWidgetRecord _content = catwg.FirstOrDefault();
                    _content.DisplayOrder = item.DisplayOrder;
                    _categoryWidget.Update(_content);
                    ids.Add(_content);
                }
                else
                {
                    if (item.Id != 0)
                    {
                        NewsContentCategoryWidgetRecord _content = new NewsContentCategoryWidgetRecord()
                        {
                            DisplayOrder = item.DisplayOrder,
                            NewsCategoryPartRecord = _service.ContentManager.Get<NewsCategoryPart>(item.Id).Record,
                            NewsCategoryWidgetPartRecord = part.Record,
                        };
                        _categoryWidget.Create(_content);
                        ids.Add(_content);
                    }
                }
            }
            foreach (var item in part.Record.ContentCategoryWidgets)
            {
                var menuwg = ids.Where(p => p.Id == item.Id);
                if (menuwg.Count() == 0)
                {
                    _categoryWidget.Delete(item);
                }
            }

            _notifier.Information(T("Category Widget edited successfully"));
            return Editor(part, shapeHelper);
        }
    }
}